package cn.com.shopec.erp.product.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.shopec.erp.base.entity.SupplierInfo;
import cn.com.shopec.erp.base.service.ISupplierAccountsService;
import cn.com.shopec.erp.base.service.ISupplierInfoService;
import cn.com.shopec.erp.base.vo.SupplierAccountsVo;
import cn.com.shopec.erp.common.constant.ProductSCMConstant;
import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.page.PageQuery;
import cn.com.shopec.erp.common.utils.DateUtil;
import cn.com.shopec.erp.common.utils.LogicUtil;
import cn.com.shopec.erp.common.utils.RandomUtil;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.product.commo.CommodityVoConvertor;
import cn.com.shopec.erp.product.commo.ProductVoConvertor;
import cn.com.shopec.erp.product.dao.ICommodityDao;
import cn.com.shopec.erp.product.dao.IProdSpecValueDao;
import cn.com.shopec.erp.product.dao.IProdSupplierDao;
import cn.com.shopec.erp.product.dao.IProductDao;
import cn.com.shopec.erp.product.entity.Commodity;
import cn.com.shopec.erp.product.entity.CommodityCat;
import cn.com.shopec.erp.product.entity.ProdSpecValue;
import cn.com.shopec.erp.product.entity.ProdSupplier;
import cn.com.shopec.erp.product.entity.Product;
import cn.com.shopec.erp.product.entity.SpecValOption;
import cn.com.shopec.erp.product.model.SpecificationInfo;
import cn.com.shopec.erp.product.service.IBrandService;
import cn.com.shopec.erp.product.service.ICommodityCatService;
import cn.com.shopec.erp.product.service.ICommodityService;
import cn.com.shopec.erp.product.service.IProdSupplierService;
import cn.com.shopec.erp.product.service.IProductService;
import cn.com.shopec.erp.product.service.ISpecValOptionService;
import cn.com.shopec.erp.product.service.ISpecificationService;
import cn.com.shopec.erp.product.vo.BrandVo;
import cn.com.shopec.erp.product.vo.CommodityCatVo;
import cn.com.shopec.erp.product.vo.CommodityVo;
import cn.com.shopec.erp.product.vo.ProdSupplierVo;
import cn.com.shopec.erp.product.vo.ProductVo1;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 
 * @ClassName: CommodityServiceImpl
 * @Description: 商品服务层实现类
 * @author: duhui
 * @date 2013-5-29 下午04:36:35
 * 
 */
@Service
public class CommodityServiceImpl implements ICommodityService {

    private static final Log log = LogFactory.getLog(CommodityServiceImpl.class);

    @Resource
    private ICommodityDao commodityDao;

    @Resource
    private IProductDao productDao;

    @Resource
    private IProdSupplierDao prodSupplierDao;

    @Resource
    private IProdSpecValueDao prodSpecValueDao;

    @Resource
    private CommodityVoConvertor commodityVoConvertor;

    @Resource
    private IProdSupplierService prodSupplierService;

    @Resource
    private ICommodityCatService commodityCatService;

    @Resource
    private IBrandService brandService;

    @Resource
    private ProductVoConvertor productVoConvertor;
    
    @Resource
    private IProductService productService;
    
    @Resource
    private ISpecificationService specificationService;
    
    @Resource
    private ISpecValOptionService specValOptionservice;
    
    @Resource
    private ISupplierInfoService supplierInfoService;
    
    @Resource
    private ISupplierAccountsService supplierAccountsService;
    
    @Override
    @Transactional
    public void addCommoProdInfo(CommodityVo commodityVo, String productString) throws Exception {
        Commodity commodity = this.addCommodity(commodityVo);

        // 添加货品和货品规格信息
        if (LogicUtil.isNotNullAndEmpty(productString)) {
            this.addProduct(commodity.getCommoNo(), productString);

        }

    }

    /**
     * 
     * @Title: addCommodity
     * @Description: 添加商品基本信息
     * @param commodityVo
     * @throws
     * @author: duhui
     * @date: 2013-5-29下午06:52:48
     */
    @Transactional
    private Commodity addCommodity(CommodityVo commodityVo) throws Exception {

        // 商品基本信息的添加
        Commodity commodity = this.commodityVoConvertor.convert2BaseCommodity(commodityVo);
        String commoNo = "";
        while(true){
            commoNo = this.getCommoNoStr();
            if (LogicUtil.isNotNull(this.commodityDao.findUniqueBy("commoNo", commoNo))) {
                continue;
            } else {
                break;
            }

        }

        commodity.setCommoNo(commoNo);
        commodity.setCreateTime(DateUtil.formatTimesTampDate(new Date()));
        commodity.setUpdateTime(DateUtil.formatTimesTampDate(new Date()));
        commodity.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);
        commodity.setCheckState(SZSCMConstant.COMMO_NOT_CHECK);

        return this.commodityDao.save(commodity);

    }
    
    /**
     * 
     * @Title: addCommodity
     * @Description: 添加商品基本信息(导入方式)
     * @param commodityVo
     * @throws
     * @author: duhui
     * @date: 2013-5-29下午06:52:48
     */
    @Transactional
    private Commodity addCommodityExcl(Commodity commodity) throws Exception {
        // 商品基本信息的添加
    	if (LogicUtil.isNotNull(commodity)) { 
    		 String commoNo = "";
    	        while (true) {
    	            commoNo = this.getCommoNoStr();
    	            if (LogicUtil.isNotNull(this.commodityDao.findUniqueBy("commoNo", commoNo))) {
    	                continue;
    	            } else {
    	                break;
    	            }
    	        }
    	        commodity.setCommoNo(commoNo);
    	        commodity.setCreateTime(DateUtil.formatTimesTampDate(new Date()));
    	        commodity.setUpdateTime(DateUtil.formatTimesTampDate(new Date()));
    	        commodity.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);
    	        commodity.setCheckState(SZSCMConstant.COMMO_OVER_CHECK);

    	        return this.commodityDao.save(commodity);
    	}else{
    		return null;
    	}
       

    }

    /**
     * 
     * @Title: addProduct
     * @Description: 添加货品和货品规格信息
     * @param productVo
     * @throws
     * @author: duhui
     * @date: 2013-5-29下午06:53:10
     */
    @Transactional
    private void addProduct(String commoNo, String productString) throws Exception {

        JSONArray productJsonArray = JSONArray.fromObject(productString);

        if (LogicUtil.isNotNullAndEmpty(productJsonArray)) {
            for (int i = 0; i < productJsonArray.size(); i++) {
                JSONObject prodJsonObj = productJsonArray.getJSONObject(i);
                Product product = new Product();
                product.setProdNo(prodJsonObj.getString("prodBarCode"));
                product.setCommoNo(commoNo);
                product.setProdBarCode(prodJsonObj.getString("prodBarCode"));
                product.setInventoryType(Integer.parseInt(prodJsonObj.getString("inventoryType")));
                product.setSaleType(Integer.parseInt(prodJsonObj.getString("saleType")));
                product.setSalePrice(Double.parseDouble(prodJsonObj.getString("salePrice")));
                product.setCasePakgSize(prodJsonObj.getString("casePakgSize"));
                product.setCreateTime(DateUtil.formatTimesTampDate(new Date()));
                product.setUpdateTime(DateUtil.formatTimesTampDate(new Date()));
                product.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);
                product.setSpecification(prodJsonObj.getString("specStr"));
                product.setUnSalePrice(Double.parseDouble(prodJsonObj.getString("unSalePrice")));
                product.setProdRate(Double.parseDouble(prodJsonObj.getString("prodRate")));
                product.setBuyNum(Integer.parseInt(prodJsonObj.getString("buyNum")));
                product.setProdUnit(prodJsonObj.getString("prodUnit"));

                String specStr = prodJsonObj.getString("specStr");
                if (LogicUtil.isNotNullAndEmpty(specStr)) {
                    String[] specManyStrArray = specStr.split(",");

                    for (int j = 0; j < specManyStrArray.length; j++) {
                        String[] specOneStrArray = specManyStrArray[j].split("-");
                        String specNo = specOneStrArray[0];
                        String optionNo = specOneStrArray[1];
                        ProdSpecValue prodSpecValue = new ProdSpecValue();
                        prodSpecValue.setProdNo(prodJsonObj.getString("prodBarCode"));
                        prodSpecValue.setSpecNo(specNo);
                        prodSpecValue.setValOptionNo(optionNo);

                        this.prodSpecValueDao.save(prodSpecValue);
                    }
                }

                this.productDao.save(product);
            }
        }

    }
    
    /**
     * 
     * @Title: addProduct
     * @Description: 添加货品和货品规格信息(EXCEL)
     * @param productVo
     * @throws
     * @author: duhui
     * @date: 2013-5-29下午06:53:10
     */
    @Transactional
    private void addProductExcel(String commoNo,List<Product> products) throws Exception {
    	
    	 Product product = new Product();
    	for (Product elemet : products) {
    		product.setProdNo(elemet.getProdNo());
	        product.setCommoNo(commoNo);
	        product.setProdBarCode(elemet.getProdBarCode());
	        product.setInventoryType(elemet.getInventoryType());
	        product.setSaleType(elemet.getSaleType());
	        product.setSalePrice(elemet.getSalePrice());
	        product.setCasePakgSize(elemet.getCasePakgSize());
	        product.setCreateTime(DateUtil.formatTimesTampDate(new Date()));
	        product.setUpdateTime(DateUtil.formatTimesTampDate(new Date()));
	        product.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);
	        product.setSpecification(elemet.getSpecification());
	        product.setUnSalePrice(elemet.getSalePrice());
	        product.setProdRate(elemet.getProdRate());
	        product.setBuyNum(elemet.getBuyNum());
	        product.setProdUnit(elemet.getProdUnit());
	        
	        if (LogicUtil.isNotNullAndEmpty(elemet.getSpecification())) {
	            String[] specManyStrArray = elemet.getSpecification().split(",");
	
	            for (int j = 0; j < specManyStrArray.length; j++) {
	                String[] specOneStrArray = specManyStrArray[j].split("-");
	                String specNo = specOneStrArray[0];
	                String optionNo = specOneStrArray[1];
	                ProdSpecValue prodSpecValue = new ProdSpecValue();
	                prodSpecValue.setProdNo(elemet.getProdBarCode());
	                prodSpecValue.setSpecNo(specNo);
	                prodSpecValue.setValOptionNo(optionNo);
	
	                this.prodSpecValueDao.save(prodSpecValue);
	            }
	        }
		}
	        
	       
	
	        this.productDao.save(product);

    }

    @Override
    public String updateCommoProdInfo(CommodityVo commodityVo, String productString) throws Exception {
        if (LogicUtil.isNotNull(commodityVo) && StringUtil.isExist(commodityVo.getCommoNo())) {
            Commodity commodity = this.commodityDao.findUniqueBy("commoNo", commodityVo.getCommoNo());
            if (LogicUtil.isNotNull(commodity)) {
                commodity.setCommoName(commodityVo.getCommoName());
                commodity.setCommoType(commodityVo.getCommoType());
                commodity.setBrandNo(commodityVo.getBrandNo());
                commodity.setDescription(commodityVo.getDescription());
                commodity.setUpdateTime(DateUtil.formatTimesTampDate(new Date()));
                if (commodity.getCheckState() == 2) {
                    commodity.setCheckState(SZSCMConstant.COMMO_NOT_CHECK);
                }
                this.commodityDao.update(commodity);
                // 添加货品和货品规格信息
                if (LogicUtil.isNotNullAndEmpty(productString)) {
                    this.updateProduct(commodity.getCommoNo(), productString);
                }
                return SZSCMConstant.SUCCESS;
            }
        }
        return SZSCMConstant.FAIL;
    }

    @Transactional
    private void updateProduct(String commoNo, String productString) throws Exception {

        JSONArray productJsonArray = JSONArray.fromObject(productString);
        if (LogicUtil.isNotNullAndEmpty(productJsonArray)) {
            for (int i = 0; i < productJsonArray.size(); i++) {
                JSONObject prodJsonObj = productJsonArray.getJSONObject(i);
                if (StringUtil.isExist(prodJsonObj.getString("prodNo"))) {
                    DetachedCriteria criteria = this.productDao.createCriteria();
                    criteria.add(Restrictions.eq("prodNo", prodJsonObj.getString("prodNo")));
                    criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
                    Product product = new Product();
                    if(this.productDao.findByCriteria(criteria).size() > 0){
                    	product = this.productDao.findByCriteria(criteria).get(0);
                    }
                    
                    if (LogicUtil.isNotNull(product)) {
                        product.setProdNo(prodJsonObj.getString("prodBarCode"));
                        product.setProdBarCode(prodJsonObj.getString("prodBarCode"));
                        product.setInventoryType(Integer.parseInt(prodJsonObj.getString("inventoryType")));
                        product.setSaleType(Integer.parseInt(prodJsonObj.getString("saleType")));
                        product.setSalePrice(Double.parseDouble(prodJsonObj.getString("salePrice")));
                        product.setCasePakgSize(prodJsonObj.getString("casePakgSize"));
                        product.setUpdateTime(DateUtil.formatTimesTampDate(new Date()));
                        product.setSpecification(prodJsonObj.getString("specStr"));
                        product.setUnSalePrice(Double.parseDouble(prodJsonObj.getString("unSalePrice")));
                        product.setProdRate(Double.parseDouble(prodJsonObj.getString("prodRate")));
                        product.setBuyNum(Integer.parseInt(prodJsonObj.getString("buyNum")));
                        product.setProdUnit(prodJsonObj.getString("prodUnit"));

                        String specStr = prodJsonObj.getString("specStr");
                        // 清除货品规格
                        this.prodSpecValueDao.deleteProdSpecValue(prodJsonObj.getString("prodNo"));
                        if (LogicUtil.isNotNullAndEmpty(specStr)) {
                            String[] specManyStrArray = specStr.split(",");
                            // 添加货品规格
                            for (int j = 0; j < specManyStrArray.length; j++) {
                                String[] specOneStrArray = specManyStrArray[j].split("-");
                                String specNo = specOneStrArray[0];
                                String optionNo = specOneStrArray[1];
                                ProdSpecValue prodSpecValue = new ProdSpecValue();
                                prodSpecValue.setProdNo(prodJsonObj.getString("prodBarCode"));
                                prodSpecValue.setSpecNo(specNo);
                                prodSpecValue.setValOptionNo(optionNo);

                                this.prodSpecValueDao.save(prodSpecValue);
                            }
                        }
                        //修改供应商货品编码
                        this.prodSupplierService.updateProdSupplierByProdNo(prodJsonObj.getString("prodNo"), prodJsonObj.getString("prodBarCode"));
                        this.productDao.update(product);
                    }
                } else {
                    Product product = new Product();
                    product.setProdNo(prodJsonObj.getString("prodBarCode"));
                    product.setCommoNo(commoNo);
                    product.setProdBarCode(prodJsonObj.getString("prodBarCode"));
                    product.setInventoryType(Integer.parseInt(prodJsonObj.getString("inventoryType")));
                    product.setSaleType(Integer.parseInt(prodJsonObj.getString("saleType")));
                    product.setSalePrice(Double.parseDouble(prodJsonObj.getString("salePrice")));
                    product.setCasePakgSize(prodJsonObj.getString("casePakgSize"));
                    product.setCreateTime(DateUtil.formatTimesTampDate(new Date()));
                    product.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);
                    product.setSpecification(prodJsonObj.getString("specStr"));
                    product.setUnSalePrice(Double.parseDouble(prodJsonObj.getString("unSalePrice")));
                    product.setProdRate(Double.parseDouble(prodJsonObj.getString("prodRate")));
                    product.setBuyNum(Integer.parseInt(prodJsonObj.getString("buyNum")));
                    product.setProdUnit(prodJsonObj.getString("prodUnit"));

                    String specStr = prodJsonObj.getString("specStr");
                    if (LogicUtil.isNotNullAndEmpty(specStr)) {
                        String[] specManyStrArray = specStr.split(",");

                        for (int j = 0; j < specManyStrArray.length; j++) {
                            String[] specOneStrArray = specManyStrArray[j].split("-");
                            String specNo = specOneStrArray[0];
                            String optionNo = specOneStrArray[1];
                            ProdSpecValue prodSpecValue = new ProdSpecValue();
                            prodSpecValue.setProdNo(prodJsonObj.getString("prodBarCode"));
                            prodSpecValue.setSpecNo(specNo);
                            prodSpecValue.setValOptionNo(optionNo);

                            this.prodSpecValueDao.save(prodSpecValue);
                        }
                    }

                    this.productDao.save(product);
                }
            }
        }
    }

    @Override
    public CommodityVo getCommodity(String commoNo) {
        return this.commodityVoConvertor.convert2BaseCommodityVo(this.commodityDao.findUniqueBy("commoNo", commoNo));
    }

    @Override
    public List<ProductVo1> getProductList(String commoNo) {
        DetachedCriteria criteria = this.productDao.createCriteria();
        if (StringUtil.isExist(commoNo)) {
            criteria.add(Restrictions.eq("commoNo", commoNo));
        }
        criteria.addOrder(Order.asc("prodBarCode"));
        criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
        return this.commodityVoConvertor.convert2BaseProductVos(this.productDao.findByCriteria(criteria));
    }

    @Override
    @Transactional
    public void addProdSupplier(String prodNo, String supplierList) throws Exception {
        // 代销货品删除    删除在360行
        //this.deleteProdSupplier(prodNo);
        
        String supplierNos = "";
        JSONArray prodSupplierJsonArray = JSONArray.fromObject(supplierList);
        if (LogicUtil.isNotNullAndEmpty(prodSupplierJsonArray)) {
            for (int i = 0; i < prodSupplierJsonArray.size(); i++) {
                JSONObject prodJsonObj = prodSupplierJsonArray.getJSONObject(i);

                ProdSupplierVo prodSupplierVo = new ProdSupplierVo();
                prodSupplierVo.setProdNo(prodNo);
                prodSupplierVo.setSupplierNo(prodJsonObj.getString("code"));
                List<ProdSupplier> prodSupplierList = this.prodSupplierService.getProdSupplierList(prodSupplierVo);
                
                if(supplierNos != "")supplierNos+=",";
                // 供应商价格是否已添加到该货品
                if (prodSupplierList.size() > 0) {
                    ProdSupplier prodSupplier = prodSupplierList.get(0);
                    prodSupplier.setSupplierNo(prodJsonObj.getString("code"));
                    prodSupplier.setGrossMargin(Double.parseDouble(prodJsonObj.getString("gcrossMargin")));
                    prodSupplier.setUntaxCostPrice(Double.parseDouble(prodJsonObj.getString("untaxCostPrice")));
                    prodSupplier.setTaxCostPrice(Double.parseDouble(prodJsonObj.getString("taxCostPrice")));
                    prodSupplier.setIsReturnedGoos(Integer.parseInt(prodJsonObj.getString("isReturnedGoods")));
                    prodSupplier.setIsSupDelivery(Integer.parseInt(prodJsonObj.getString("isSupDelivery")));
                    this.prodSupplierDao.update(prodSupplier);
                    supplierNos += "'"+prodSupplier.getSupplierNo()+"'";
                } else {
                    ProdSupplier prodSupplier = new ProdSupplier();
                    prodSupplier.setProdNo(prodNo);
                    prodSupplier.setSupplierNo(prodJsonObj.getString("code"));
//                    prodSupplier.setGrossMargin(Double.parseDouble(prodJsonObj.getString("gcrossMargin")));
//                    prodSupplier.setUntaxCostPrice(Double.parseDouble(prodJsonObj.getString("untaxCostPrice")));
//                    prodSupplier.setTaxCostPrice(Double.parseDouble(prodJsonObj.getString("taxCostPrice")));
                    prodSupplier.setIsReturnedGoos(Integer.parseInt(prodJsonObj.getString("isReturnedGoods")));
                    prodSupplier.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);
                    prodSupplier.setIsSupDelivery(Integer.parseInt(prodJsonObj.getString("isSupDelivery")));
                    this.prodSupplierDao.save(prodSupplier);
                    supplierNos += "'"+prodSupplier.getSupplierNo()+"'";
                }
            }
        }
        //删除供应商价格设置
        this.prodSupplierDao.delectProdSuppliers(prodNo, supplierNos);
    }
    
    /**
     * 导入版的批量设置供应商
     * @param prodNo
     * @param supplierList
     * @throws Exception
     */
    @Override
    @Transactional
    public void addProdSupplierExcl(String prodNo, ProdSupplierVo supplierList) throws Exception {
        String supplierNos = "";
        JSONArray prodSupplierJsonArray = JSONArray.fromObject(supplierList);
        if (LogicUtil.isNotNullAndEmpty(prodSupplierJsonArray)) {
            for (int i = 0; i < prodSupplierJsonArray.size(); i++) {
                JSONObject prodJsonObj = prodSupplierJsonArray.getJSONObject(i);

                ProdSupplierVo prodSupplierVo = new ProdSupplierVo();
                prodSupplierVo.setProdNo(prodNo);
                prodSupplierVo.setSupplierNo(prodJsonObj.getString("code"));
                List<ProdSupplier> prodSupplierList = this.prodSupplierService.getProdSupplierList(prodSupplierVo);
                
                if(supplierNos != "")supplierNos+=",";
                // 供应商价格是否已添加到该货品
                if (prodSupplierList.size() > 0) {
                    ProdSupplier prodSupplier = prodSupplierList.get(0);
                    prodSupplier.setSupplierNo(prodJsonObj.getString("code"));
                    prodSupplier.setGrossMargin(Double.parseDouble(prodJsonObj.getString("gcrossMargin")));
                    prodSupplier.setUntaxCostPrice(Double.parseDouble(prodJsonObj.getString("untaxCostPrice")));
                    prodSupplier.setTaxCostPrice(Double.parseDouble(prodJsonObj.getString("taxCostPrice")));
                    prodSupplier.setIsReturnedGoos(Integer.parseInt(prodJsonObj.getString("isReturnedGoods")));
                    prodSupplier.setIsSupDelivery(Integer.parseInt(prodJsonObj.getString("isSupDelivery")));
                    this.prodSupplierDao.update(prodSupplier);
                    supplierNos += "'"+prodSupplier.getSupplierNo()+"'";
                } else {
                    ProdSupplier prodSupplier = new ProdSupplier();
                    prodSupplier.setProdNo(prodNo);
                    prodSupplier.setSupplierNo(prodJsonObj.getString("code"));
                    prodSupplier.setGrossMargin(Double.parseDouble(prodJsonObj.getString("gcrossMargin")));
                    prodSupplier.setUntaxCostPrice(Double.parseDouble(prodJsonObj.getString("untaxCostPrice")));
                    prodSupplier.setTaxCostPrice(Double.parseDouble(prodJsonObj.getString("taxCostPrice")));
                    prodSupplier.setIsReturnedGoos(Integer.parseInt(prodJsonObj.getString("isReturnedGoods")));
                    prodSupplier.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);
                    prodSupplier.setIsSupDelivery(Integer.parseInt(prodJsonObj.getString("isSupDelivery")));
                    this.prodSupplierDao.save(prodSupplier);
                    supplierNos += "'"+prodSupplier.getSupplierNo()+"'";
                }
            }
        }
        //删除供应商价格设置
        this.prodSupplierDao.delectProdSuppliers(prodNo, supplierNos);
    }

    /**
     * 代销货品删除供应商设置价格
     * 
     * @param prodNo
     * @throws Exception
     * gaoyaxiong 2013-6-19
     */
    @Transactional
    public void deleteProdSupplier(String prodNo) throws Exception {
    	DetachedCriteria criteria = this.productDao.createCriteria();
        if (StringUtil.isExist(prodNo)) {
            criteria.add(Restrictions.eq("prodNo", prodNo));
            criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
            Product product = new Product();
            if(this.productDao.findByCriteria(criteria).size() > 0){
            	product = this.productDao.findByCriteria(criteria).get(0);
            	if (product.getSaleType() == SZSCMConstant.AGENCY_TYPE_2) {
                    ProdSupplierVo prodSupplierVo = new ProdSupplierVo();
                    prodSupplierVo.setProdNo(prodNo);
                    List<ProdSupplier> prodSupplierList = this.prodSupplierService.getProdSupplierList(prodSupplierVo);
                    for (ProdSupplier prodSupplier : prodSupplierList) {
                        prodSupplier.setDeleteFlag(SZSCMConstant.DELETE_FLAG_YES);
                        this.prodSupplierDao.update(prodSupplier);
                    }
                }
            }
        }
    }

    @Override
    public PageFinder<CommodityVo> pageFinderCommodity(CommodityVo commodity1, PageQuery pageQuery)
            throws Exception {

        DetachedCriteria detachedCriteria = this.commodityDao.createCriteria();
        detachedCriteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));// 未删除
        if (null != commodity1) {
            // 商品名称
            if (LogicUtil.isNotNullAndEmpty(commodity1.getCommoName())) {
                detachedCriteria.add(Restrictions.like("commoName", commodity1.getCommoName(), MatchMode.ANYWHERE));
            }

            // 商品编码
            if (LogicUtil.isNotNullAndEmpty(commodity1.getCommoNo())) {
                detachedCriteria.add(Restrictions.like("commoNo", commodity1.getCommoNo(), MatchMode.ANYWHERE));
            }
            // 审核状态
            if(commodity1.getCheckState().intValue()!=-1)
            {
                detachedCriteria.add(Restrictions.eq("checkState", commodity1.getCheckState()));
            }
            if(StringUtil.isExist(commodity1.getCreateStartDate())){
            	//detachedCriteria.add(Restrictions.ge("createTime", commodity1.getCreateStartDate()));
            	detachedCriteria.add(Restrictions.gt("createTime", commodity1.getCreateStartDate()));
            }
            if(StringUtil.isExist(commodity1.getCreateEndDate())){
            	String endTime =  DateUtil.getDateNextDay(commodity1.getCreateEndDate());
            	detachedCriteria.add(Restrictions.lt("createTime", endTime));
            }
            if(StringUtil.isExist(commodity1.getProdNo())){
            	String sql = "this_.commo_no = (select p.commo_no from TBL_PRODUCT p where p.prod_no='"+commodity1.getProdNo()+"' and p.delete_flag=1)";
            	detachedCriteria.add(Restrictions.sqlRestriction(sql));
            }
            
        }
        // 按创建时间排序
        detachedCriteria.addOrder(Order.desc("createTime"));
        PageFinder<Commodity> pagedCommodityList = this.commodityDao.pagedByCriteria(detachedCriteria,
                pageQuery.getPage(), pageQuery.getPageSize());

        return this.commodityVoConvertor.convert2PagedCommodityVos(pagedCommodityList);
    }

    @Override
    public PageFinder<Commodity> pagedCommodityByCheckState(Commodity commodity1, PageQuery pageQuery) throws Exception {

        DetachedCriteria detachedCriteria = this.commodityDao.createCriteria();
        detachedCriteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));// 未删除
        if (null != commodity1) {
            // 商品名称
            if (LogicUtil.isNotNullAndEmpty(commodity1.getCommoName())) {
                detachedCriteria.add(Restrictions.like("commoName", commodity1.getCommoName(), MatchMode.ANYWHERE));
            }

            // 商品编码
            if (LogicUtil.isNotNullAndEmpty(commodity1.getCommoNo())) {
                detachedCriteria.add(Restrictions.like("commoNo", commodity1.getCommoNo(), MatchMode.ANYWHERE));
            }
        }
        detachedCriteria.add(Restrictions.eq("checkState", SZSCMConstant.COMMO_OVER_CHECK));
        // 按创建时间排序
        // detachedCriteria.addOrder(Order.desc("createTime"));
        PageFinder<Commodity> pagedCommodityList = this.commodityDao.pagedByCriteria(detachedCriteria,
                pageQuery.getPage(), pageQuery.getPageSize());
        if (LogicUtil.isNotNull(pagedCommodityList)) {
            if (LogicUtil.isNotNullAndEmpty(pagedCommodityList.getData())) {
                for (Commodity commodity : pagedCommodityList.getData()) {
                    this.initializeProduct(commodity, true, false);
                }
            }
        }
        return pagedCommodityList;
    }

    /**
     * 
     * @MethodName initializeProductOfReturnedPO
     * @Description 初始化商品对应的货品信息
     * @author chengui
     * @date 2013-5-25 上午11:06:17
     * @param returnedPO
     * @throws Exception
     */
    public void initializeProduct(Commodity commodity, boolean initializeProduct, boolean initializeHistory)
            throws Exception {
        if (initializeProduct) {
            Hibernate.initialize(commodity.getProducts());
        }
        if (initializeHistory) {
            Hibernate.initialize(commodity.getProducts());
        }
    }

    @Override
    public List<Product> getAllProductByCommoNo(String commoNo) {
        DetachedCriteria detachedCriteria = this.productDao.createCriteria();
        detachedCriteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
        detachedCriteria.add(Restrictions.eq("commoNo", commoNo));
        return this.productDao.findByCriteria(detachedCriteria);
    }

    @Override
    public Commodity getCommodityByCommoNo(String commoNo) {
        return this.commodityDao.findUniqueBy("commoNo", commoNo);
    }

    @Override
    public ProductVo1 getProduct(String prodNo) throws Exception {
    	 ProductVo1 productVo=null;
    	
    	 DetachedCriteria criteria = this.productDao.createCriteria();
         criteria.add(Restrictions.eq("prodNo", prodNo));
         criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
         List<Product> products=this.productDao.findByCriteria(criteria);
         if(LogicUtil.isNotNullAndEmpty(products)){
        	 productVo=this.productVoConvertor.convert2ProductVo(products.get(0));
         }
       
        return productVo;
    }

    @Override
    @Transactional
    public void delCommodity(String commonNo) throws Exception {

        Commodity dity = this.getCommodityByCommoNo(commonNo);
        List<Product> list = this.getAllProductByCommoNo(commonNo);
        if (null != list && list.size() > 0) {
            for (Product p : list) {
                p.setDeleteFlag(SZSCMConstant.DELETE_FLAG_YES);
                this.productDao.update(p);
            }
            dity.setDeleteFlag(SZSCMConstant.DELETE_FLAG_YES);// 已删除
        } else {
            dity.setDeleteFlag(SZSCMConstant.DELETE_FLAG_YES);// 已删除
        }
        this.commodityDao.update(dity);
    }

    /*
     * (no-Javadoc) <p>Title: updateCommodityByCheck</p> <p>Description: </p>
     * 
     * @param commoNo
     * 
     * @param checkState
     * 
     * @return
     * 
     * @throws Exception
     * 
     * @see
     * cn.com.shopec.erp.product.service.ICommodityService#updateCommodityByCheck
     * (java.lang.String, int)
     */
    @Override
    @Transactional
    public int checkCommodity(String commoNo, int checkState) throws Exception {

        int res = SZSCMConstant.FAIL_INT;
        if (checkState != 1 && checkState != 2) {
            return -1;
        }
        try {
            Commodity commo = this.getCommodityByCommoNo(commoNo);
            if (commo != null) {
                if (checkState == 1) {
//                    // 判断同步数据是否成功，成功执行审核操作
//                    if (this.commodityWMSService.sendCommodityCreateOrUpdate(commoNo)) {
                        commo.setCheckState(checkState);
                        commo.setUpdateTime(DateUtil.formatDateByFormat(new Date(), DateUtil.TIMESTAMP_PATTERN));
                        this.commodityDao.update(commo);
                        res = SZSCMConstant.SUCCESS_INT;
//                    } else {
//                        res = -3; // 同步数据异常的标志
//                    }
                } else if (checkState == 2) {
                    commo.setCheckState(checkState);
                    commo.setUpdateTime(DateUtil.formatDateByFormat(new Date(), DateUtil.TIMESTAMP_PATTERN));
                    this.commodityDao.update(commo);
                    res = SZSCMConstant.SUCCESS_INT;
                }

            } else {
                res = -2;
            }

        } catch (Exception e) {
            log.error("checkCommodity:" + e.getMessage(), e);
        } finally {

        }

        return res;

    }

    @Override
    public List<CommodityVo> getCommodityList(CommodityVo commodityVo) {
        DetachedCriteria criteria = this.commodityDao.createCriteria();
        if (LogicUtil.isNotNull(commodityVo)) {
            if (StringUtil.isExist(commodityVo.getCatNo())) {
                criteria.add(Restrictions.eq("catNo", commodityVo.getCatNo()));
            }
            if (StringUtil.isExist(commodityVo.getBrandNo())) {
                criteria.add(Restrictions.eq("brandNo", commodityVo.getBrandNo()));
            }
            if (StringUtil.isExist(commodityVo.getCommoName())) {
                criteria.add(Restrictions.like("commoName", "%" + commodityVo.getCommoName() + "%"));
            }
        }
        criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
        return this.commodityVoConvertor.convert2BaseCommodityVos(this.commodityDao.findByCriteria(criteria));
    }

    /**
     * 
     * @Title: getCommoNo
     * @Description: 随机生成不重复的6位数
     * @param commoNo
     * @return
     * @throws Exception
     * @throws
     * @author: duhui
     * @date: 2013-7-1下午05:02:28
     */

    private String getCommoNoStr() {
        int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        Random rand = new Random();
        for (int i = 9; i > 2; i--) {
            int index = rand.nextInt(i);
            int tmp = array[index];
            array[index] = array[i - 1];
            array[i - 1] = tmp;
        }
        Integer result = 0;
        for (int i = 0; i < 6; i++) {
            result = result.intValue() * 10 + array[i];
        }

        return result.toString();
    }

    /**
     * 
     * @Title: getProductNo
     * @Description: 生成货品编号
     * @return
     * @throws Exception
     * @throws
     * @author: duhui
     * @date: 2013-5-29下午08:23:45
     */
    private String getProductNo(String commoNo) throws Exception {
        String productNo = "";
        CommodityVo commodity = this.getCommodity(commoNo);

        // 分类
        CommodityCatVo catVo = new CommodityCatVo();
        catVo.setCatNo(commodity.getCatNo());
        productNo += this.commodityCatService.getCommodityCatList(catVo).get(0).getNo();

        // 品牌
        BrandVo brandVo = this.brandService.getBrand(commodity.getBrandNo());
        productNo += brandVo.getNo();

        productNo += RandomUtil.getRandomNumberStr(5);
        return productNo;
    }

    /**
     * 根据货品编码获取商品信息
     */
    @Override
    public Commodity getCommondityByProNo(String prodNo) throws Exception {
        return this.getCommodityByCommoNo(this.getProduct(prodNo).getCommoNo());
    }

    @Override
    @Transactional
    public String checkNoCommodity(String commoNo, int checkState, String desc) throws Exception {
        String result = SZSCMConstant.FAIL;

        Commodity commo = this.getCommodityByCommoNo(commoNo);
        if (LogicUtil.isNotNull(commo)) {
            commo.setCheckState(checkState);
            commo.setCheckReason(desc);
            commo.setUpdateTime(DateUtil.formatDateByFormat(new Date(), DateUtil.TIMESTAMP_PATTERN));
            this.commodityDao.update(commo);
            result = SZSCMConstant.SUCCESS;
        }

        return result;
    }

    public static void main(String[] args) {
        CommodityServiceImpl commoditySericeService = new CommodityServiceImpl();
        int i = 11;
        System.out.println(commoditySericeService.getCommoNoStr() + i);
    }
    
    @Override
    public List getCommodityDetail(CommodityVo commodityVo){
    	return this.commodityDao.CommodityDetail(commodityVo);
    }

    /**
     * 导入商品货品
     */
	@Override
	@Transactional
	public String importProductBarCodes(List<List<Object>> excelData) throws Exception {
		//返回内容
		String result = "";
		// 父商品名称
		String checkCommoName = "";
		// 父商品ID
		String checkCommoNo = "";
		
		// 商品货品集合
		List<Product> products = new ArrayList<Product>();
		// 商品
		Commodity commodity = new Commodity();
		// 货品
		Product product = new Product();
		//供应商
		ProdSupplier supplier2 = new ProdSupplier();
		//供应商集合
		List<ProdSupplier> supList = new ArrayList<ProdSupplier>();
		//标识导入行数
		int index=1;
		for (List<Object> list : excelData) {
			
			// 含税零售价
			Double retailTaxincluded;

			// 1.检查分类是否存在
			Commodity com = checkCommodityCat(list, commodity);
			if (com != null) {
				commodity.setCatNo(com.getCatNo());
			}else{
				result="第("+index+")行商品分类不存在!";
				continue;
			}

			// 2.商品名称校验
			try{
				if(!StringUtil.isEmpty(list.get(1).toString())){
					commodity.setCommoName(list.get(1).toString().trim());
				}else{
					result="第("+index+")行商品名称为空!";
					continue;
				}
			}catch(Exception e){
				e.printStackTrace();
				result="第("+index+")行商品名称为空!";
				continue;
			}
			

			// 3.商品类型
			try{
				if(!StringUtil.isEmpty(list.get(2).toString())){
					if (list.get(2).toString().trim().equals(ProductSCMConstant.COMMODITYTYPE)) {
						commodity.setCommoType(ProductSCMConstant.COMMODITYTYPE_NO);
						product.setInventoryType(ProductSCMConstant.INVENTORYTYPE_REALLIBRARY);
					} else if (list.get(2).toString().trim().equals(ProductSCMConstant.COMMODITYTYPE_VIRTUAL)) {
						commodity.setCommoType(ProductSCMConstant.COMMODITYTYPE_VIRTUAL_NO);
						product.setInventoryType(ProductSCMConstant.INVENTORYTYPE_VIRTUALLIBRARY);
					} else {
						result="第("+index+")行商品类型不存在!";
						continue;
					}
				} else {
					result="第("+index+")行商品类型为空!";
					continue;
				}
				
			}catch(Exception e){
				e.printStackTrace();
				result="第("+index+")行商品类型为空!";
				continue;
			}
			
			// 4.品牌
			try{
				if(!StringUtil.isEmpty(list.get(3).toString())){
					BrandVo brand = brandService.getBrandName(list.get(3).toString().trim());
					if (brand == null) {
						result="第("+index+")行商品品牌不存在!";
						continue;
					} else {
						commodity.setBrandNo(brand.getBrandNo());
					}
				} else {
					result="第("+index+")行商品品牌为空!";
					continue;
				}
			}catch(Exception e){
				e.printStackTrace();
				result="第("+index+")行商品品牌为空!";
				continue;
			}

			// 5.商品描述
		try{
			if(!StringUtil.isEmpty(list.get(4).toString())){
				commodity.setDescription(list.get(4).toString());
			} else {
				result="第("+index+")行商品描述为空!";
				continue;
			}
		}catch(Exception e){
			e.printStackTrace();
			result="第("+index+")行商品描述为空!";
			continue;
		}
			

		// 6货品规格
		try{
			if(!StringUtil.isEmpty(list.get(5).toString())){
				String[] array = list.get(5).toString().trim().split("，");
				if (array.length <= 0) {
					result="第("+index+")行商品规格不存在!";
					continue;
				}
				for (int i = 0; i < array.length; i++) {
					List<SpecificationInfo> specificationList = specificationService.getSpecificationsCatName(array[i]);
					if (specificationList.size() > 0) {
						for (SpecificationInfo speci : specificationList) {
							commodity.setCatNo(speci.getCatNo());
						}
					} else {
						result="第("+index+")行商品规格不存在!";
						continue;
					}
				}
			}else{
				result="第("+index+")行商品规格为空!";
				continue;
			}
			
		}catch(Exception e){
			e.printStackTrace();
			result="第("+index+")行商品规格为空!";
			continue;
		}
			

			// 7.货品条码
		  if(!StringUtil.isEmpty(list.get(6).toString())){
				String bool = productService.validationRepeatProdBarCode(list.get(6).toString().trim());
				if (!bool.equals("") && !bool.equals(SZSCMConstant.SUCCESS)) {
					product.setProdBarCode(list.get(6).toString().trim());
					product.setProdNo(list.get(6).toString().trim());
				} else {
					result="第("+index+")行货品条码已存在!";
					continue;
				}
			} else {
				result="第("+index+")行货品条码为空!";
				continue;
			}

			// 8.销售类型
		  if(!StringUtil.isEmpty(list.get(7).toString())){
				if (list.get(7).toString().trim().equals(ProductSCMConstant.COMMODITY_SALETYPE)) {
					product.setSaleType(ProductSCMConstant.COMMODITY_SALETYPE_No);
				} else {
					result="第("+index+")行货品销售类型不存在!";
					continue;
				}
			} else {
				result="第("+index+")行货品销售类型为空!";
				continue;
			}

			// 9.含税零售价
		  if(!StringUtil.isEmpty(list.get(8).toString())){
				retailTaxincluded = (Double) list.get(8);
				product.setSalePrice((Double) list.get(8));
			} else {
				result="第("+index+")行货品含税零售价为空!";
				continue;
			}
			// 10.税率
		  if(!StringUtil.isEmpty(list.get(9).toString())){
				//税率
				product.setProdRate((Double)list.get(9));
				double 	prod = (double)list.get(9);
				float prodRate = (float)prod;
				// 未税零售价
//				product.setUnSalePrice((retailTaxincluded )/(1+(prodRate)/100));
				 BigDecimal bg = new BigDecimal((retailTaxincluded )/(1+(prodRate)/100)).setScale(2, RoundingMode.UP);
				 product.setUnSalePrice(bg.doubleValue());
				
			}
			// 11.最低订货数量
		  if(!StringUtil.isEmpty(list.get(10).toString())){
				product.setBuyNum(Integer.valueOf(((Double) list.get(10)).intValue()));
			} else {
				result="第("+index+")行货品最低订货数量为空!";
				continue;
			}
			// 12.箱包装规格
//			if (list.get(11) != null) {
		  if(!StringUtil.isEmpty(list.get(11).toString())){
				product.setCasePakgSize((String) list.get(11));
			} else {
				result="第("+index+")行货品箱包装规格为空!";
				continue;
			}
			// 13.单位
		  if(!StringUtil.isEmpty(list.get(12).toString())){
				product.setProdUnit((String) list.get(12).toString().trim());
			}else{
				result="第("+index+")行货品单位为空!";
				continue;
			}
			
			// 14规格内容
		  if(!StringUtil.isEmpty(list.get(13).toString())){
				String[] sz = list.get(13).toString().trim().split("，");
				for (int i = 0; i < sz.length; i++) {
					SpecValOption apecval = specValOptionservice.getSpecValOption(sz[i]);
					if (apecval != null) {
						String specno = apecval.getSpecNo();
						String optionno = apecval.getOptionNo();
						product.setSpecification(specno + "-" + optionno);
					} else {
						continue;
					}
				}
			} else {
				result="第("+index+")行货品规格内容为空!";
				continue;
			}
			// 15供应商名称
		  if(!StringUtil.isEmpty(list.get(14).toString())){
				String[] array = list.get(14).toString().trim().split("，");
				for (int i = 0; i < array.length; i++) {
					//1.首先去查询是否存在
					SupplierInfo sup = supplierInfoService.getSupplierInfoBySupName(array[i]);
					if (sup != null && sup.getState().equals("0")) {
						//2.存在则去TBL_SUPPLIER_ACCOUNTS表中根据品牌编号(no)查询是否有该供应商
						//(1)根据品牌id拿到品牌编号
						BrandVo bran = brandService.getBrandName(list.get(3).toString());
						if(bran!=null){
							//品牌编号
							List<SupplierAccountsVo> supplierList = supplierAccountsService.getSupplierAccountsListByNo(bran.getNo());
							if(supplierList!=null){
								for (int j = 0; j < supplierList.size(); j++) {
									if(supplierList.get(j).getSupName().equals(array[i])){
										supplier2.setSupplierNo(sup.getCode());//设置供应商编号
										supplier2.setProdNo(product.getProdNo());//设置货品编号
										supList.add(supplier2);
									}else{
										result="第("+index+")行品牌与供应商不对应!";
										continue;
									}
								}
							}else{
								result="第("+index+")行供应商没有与该商品的品牌建立关系!";
							}
						}else{
							result="第("+index+")行供应商没有与该商品的品牌建立关系!";
							continue;
						}
						
					} else {
						result="第("+index+")行货品供应商不存在!";
						continue;
					}
				}
			} else {
				result="第("+index+")行货品供应商名称为空!";
				continue;
			}
				
			//第一条记录
			if(checkCommoName.equals("") && checkCommoNo.equals("")){
				products.add(product);//把所有货品存放到集合
				this.addCommodityExcl(commodity);//保存商品基本信息
				this.addProductExcel(commodity.getCommoNo(),products);//货品规格保存
				//设置供应商
//				setProdSupplierExcl(supList, list);
				result = setProdSupplierExcl(supList, list,index,result);
				
				checkCommoName = commodity.getCommoName();//保存父节点
				checkCommoNo = commodity.getCommoNo();//保存父节点id
				commodity = new Commodity();
				product = new Product();
				supplier2 = new ProdSupplier(); 
				supList.clear();
				products.clear();
			}else{
				//第N条记录
				if(checkCommoName.equals(commodity.getCommoName()) && !commodity.getCommoName().equals("") ){
					products.add(product);//把所有货品存放到集合
//					this.addCommodityExcl(commodity);//保存商品基本信息
					this.addProductExcel(checkCommoNo,products);//货品规格保存
					//设置供应商
//					setProdSupplierExcl(supList, list);
				    result = setProdSupplierExcl(supList, list,index,result);
					
					commodity = new Commodity();
					product = new Product();
					supplier2 = new ProdSupplier();
					products.clear();
					supList.clear();
				}else{
					products.add(product);//把所有货品存放到集合
					this.addCommodityExcl(commodity);//保存商品基本信息
					this.addProductExcel(commodity.getCommoNo(),products);//货品规格保存
					//设置供应商
//					setProdSupplierExcl(supList, list);
					 result = setProdSupplierExcl(supList, list,index,result);
					//更新父商品信息
					checkCommoName = commodity.getCommoName();//保存父节点
					checkCommoNo = commodity.getCommoNo();//保存父节点id
					commodity = new Commodity();
					product = new Product();
					supplier2 = new ProdSupplier();
					products.clear();
					supList.clear();
				}
			}
			index++; 
		}
		return result;
	}

	private String setProdSupplierExcl(List<ProdSupplier> supList, List<Object> list,int index,String result) throws Exception {
			// 16供应商是否发货
		 	if (list.get(15) != null && !list.get(14).toString().equals("")) {
		 		 ProdSupplier supplierinfo = supList.get(0);
				 if(list.get(15).toString().equals(ProductSCMConstant.ISSUPDELIVERYFIRST)){
					 supplierinfo.setIsSupDelivery(ProductSCMConstant.ISSUPDELIVERY_FIRST);//可发货
				 }else{
					 supplierinfo.setIsSupDelivery(ProductSCMConstant.ISSUPDELIVERY_ZEON);//不可发货
				 }
				 supplierinfo.setIsReturnedGoos(ProductSCMConstant.ISRETURNED_GOOS);//默认可退货
				 supplierinfo.setDeleteFlag(SZSCMConstant.DELETE_FLAG_NO);
				 this.prodSupplierDao.save(supplierinfo);
			}else{
				result="第("+index+")行货品没有设置供应商是否(供应商发货)!";
			}
		return  result;
	}

	/**
	 * 检查商品信息是否符合要求
	 */
	/*private void validateCommodityInfo(List<Object> list,Commodity commodity,Product product ) {
		//含税零售价
		Double retailTaxincluded = 0.00;
		//税率
		Double prodRate = 0.00;
		
		//1.检查分类是否存在
		Commodity com =  checkCommodityCat(list,commodity);
		if(com!=null){
			commodity.setCatNo(com.getCatNo());
		}
		
		//2.商品名称校验
		Commodity getCommo = getCommodityInfo(list.get(1).toString());
		if(getCommo==null){
			continue;
		}
		
		//3.商品类型
		if(!list.get(2).toString().equals("") && list.get(2)!=null){
			if(list.get(2).toString().equals(ProductSCMConstant.COMMODITYTYPE)){
				commodity.setCommoType(ProductSCMConstant.COMMODITYTYPE_NO);
				product.setInventoryType(ProductSCMConstant.INVENTORYTYPE_REALLIBRARY);
			}else if(list.get(2).toString().equals(ProductSCMConstant.COMMODITYTYPE_VIRTUAL)){
				commodity.setCommoType(ProductSCMConstant.COMMODITYTYPE_VIRTUAL_NO);
				product.setInventoryType(ProductSCMConstant.INVENTORYTYPE_VIRTUALLIBRARY);
			}else{
				continue;
			}
			
		}else{
			continue;
		}
		//4.品牌
		if(!list.get(3).toString().equals("") && list.get(3)!=null){
//			List<CommodityCatVo> commoditycatList = commodityCatService.getCommodityCatNo(commodity.getCommoName());
		BrandVo brand =	brandService.getBrandName(list.get(3).toString());
			if(brand==null){
				continue;
			}else{
				commodity.setBrandNo(brand.getBrandNo());
			}
		}else{
			continue;
		}
		
		//5.商品描述
		if(!list.get(4).toString().equals("") && list.get(4)!=null){
			commodity.setDescription(list.get(4).toString());
		}else{
			continue;
		}
		
		//6货品规格
		if(!list.get(5).toString().equals("") && list.get(5)!=null){
			String[] array = list.get(5).toString().split("，");
			if(array.length<=0){
				continue;
			}
			
			for (int i = 0; i < array.length; i++) {
				List<SpecificationInfo> specificationList = specificationService.getSpecificationsCatName(array[i]);
				if(specificationList.size()>0){
					for (SpecificationInfo speci : specificationList) {
						commodity.setCatNo(speci.getCatNo());
					}
				}else{
					continue;
				}
			}
			
		}
		
		//7.货品条码
		if(!list.get(6).toString().equals("") && list.get(6)!=null){
			String bool = productService.validationRepeatProdBarCode(list.get(6).toString());
			if(!bool.equals("") && !bool.equals(SZSCMConstant.SUCCESS)){
				product.setProdBarCode(list.get(6).toString());
				product.setProdNo(list.get(6).toString());
			}else{
				continue;
			}
		}else{
			continue;
		}
		
		//8.销售类型
		if(list.get(7).toString()!=null && list.get(7)!=null){
			if(list.get(7).toString().equals(ProductSCMConstant.COMMODITY_SALETYPE)){
				product.setSaleType(ProductSCMConstant.COMMODITY_SALETYPE_No);
			}else{
				continue;
			}
		}else{
			continue;
		}
		
		//9.含税零售价
		if(!list.get(8).toString().equals("") && list.get(8)!=null){
			retailTaxincluded = (Double) list.get(8);
		}else{
			continue;
		}
		//10.税率
		if(!list.get(9).toString().equals("") && list.get(9)!=null){
			prodRate = (Double) list.get(9);
			//未税零售价
			product.setSalePrice(retailTaxincluded * prodRate);
		}
		//11.最低订货数量
		if(!list.get(10).toString().equals("") && list.get(10)!=null){
			product.setBuyNum(Integer.valueOf(((Double)list.get(10)).intValue()));
		}else{
			continue;
		}
		//12.箱包装规格
		if(!list.get(11).toString().equals("") && list.get(11)!=null){
			product.setCasePakgSize((String)list.get(11));
		}else{
			continue;
		}
		//13.单位
		if(!list.get(12).toString().equals("") && list.get(12)!=null){
			product.setProdUnit((String)list.get(12));
		}
		//14规格内容
		if(!list.get(13).toString().equals("") && list.get(13)!=null){
			 String[] sz = list.get(13).toString().split("，");
			 for (int i = 0; i < sz.length; i++) {
				SpecValOption apecval = ispecValOptionservice.getSpecValOption(sz[i]);
				if(apecval!=null){
					String specno = apecval.getSpecNo();
					String optionno = apecval.getOptionNo();
					product.setSpecification(specno+"-"+optionno);
				}else{
					continue;
				}
			}
		}else{
			continue;
		}
		//15供应商名称
		if(!list.get(14).toString().equals("") && list.get(14)!=null){
			 String[] array = list.get(14).toString().split("，");
			 for (int i = 0; i < array.length; i++) {
				  ProdSupplierVo prodsup = prodSupplierService.getPuNoByPurchaseRequest(array[i]);
				  if(prodsup!=null){
					  this.addProdSupplierExcl(prodsup.getProdNo(), prodsup);
				  }else{
					  continue;
				  }
				 
				 
				
			}
		}else{
			continue;
		}
		
		//16供应商是否发货
		
	}*/

	/**
	 * 迭代检查导入分类是否存在
	 */
	private Commodity checkCommodityCat(List<Object> list,Commodity commodity) {
		//定义分类是否都存在标识
//		if(list.get(0)!=null && !list.get(0).toString().equals("")){
		if(!StringUtil.isEmpty(list.get(0).toString())){
			String[] array = list.get(0).toString().trim().split(",");
			if(array.length>0){
				//父分类编号
				String parentCatNo="";
				CommodityCatVo catVo=new CommodityCatVo();
				catVo.setCatName(array[0].toString());
				//通过名称查询出一级分类对象
				List<CommodityCat> firstCats = commodityCatService.getCommodityByCat(catVo);
				if(firstCats.size()>0){
					CommodityCat cat=firstCats.get(0);
					//保存一级分类（默认取第一级分类）
					parentCatNo=cat.getCatNo();
					//设置商品的分类编号
					commodity.setCatNo(parentCatNo);
					for (int i = 1; i < array.length; i++) {
						if(array[i]!=null){
							catVo.setCatName(array[i].toString());
							catVo.setCatPno(parentCatNo);
							//通过父分类编号和分类名称确认子级分类（唯一性查询）
							List<CommodityCat> cats = commodityCatService.getCommodityByCat(catVo);
							if(cats.size()>0){
								parentCatNo=cats.get(0).getCatNo();
								//设置商品的分类编号
								commodity.setCatNo(cat.getCatNo());
							}else{
								continue;
							}
						}else{
							continue;
						}
					}
					//所有分类都遍历完将标识改为成功
//					flag=true;
				}
			}
		}
		return commodity;
	}

	/**
	 * 根据商品名称查询商品信息
	 */
	@Override
	public Commodity getCommodityInfo(String commodName) {
		Commodity commodity = null;
		if(!commodName.equals("") && commodName!=null){
	        DetachedCriteria criteria = this.commodityDao.createCriteria();
	        criteria.add(Restrictions.eq("commoName", commodName));
	        criteria.add(Restrictions.eq("deleteFlag", SZSCMConstant.DELETE_FLAG_NO));
	        List<Commodity> commodityList = this.commodityDao.findByCriteria(criteria);
	        if (LogicUtil.isNotNullAndEmpty(commodityList)) {
	        	commodity = commodityList.get(0);
	        }
		}
        return commodity;
	}
    
}